package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.entity.*;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 王磊
 * @date 2022/5/9
 */
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private SetmealService setmealService;

    /**
     * 菜品分页查询
     */
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        Page<Dish> DishPage = new Page(page, pageSize);
        Page<DishDto> DishDtoPage = new Page<>();

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.like(name != null, Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        dishService.page(DishPage, queryWrapper);

        BeanUtils.copyProperties(DishPage, DishDtoPage, "records");

        List<Dish> records = DishPage.getRecords();

        List<DishDto> lists = records.stream().map((itam) -> {
                    DishDto dishDto = new DishDto();
                    BeanUtils.copyProperties(itam, dishDto);
                    Long categoryId = itam.getCategoryId();
                    Category category = categoryService.getById(categoryId);
                    dishDto.setCategoryName(category.getName());
                    return dishDto;
                }
        ).collect(Collectors.toList());
        DishDtoPage.setRecords(lists);
        return R.success(DishDtoPage);
    }

    /**
     * 删除菜品
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long[] ids) {
        //判断是否关联了套餐
        LambdaQueryWrapper<Setmeal> QueryWrapper = new LambdaQueryWrapper<>();
        QueryWrapper.eq(Setmeal::getCategoryId, ids);
        int count = setmealService.count(QueryWrapper);
        if (count > 0) {
            return R.error("当前菜品关联了套餐,不能删除");
        }
        List<Long> list = Arrays.asList(ids);
        dishService.removeByIds(list);
        return R.success("删除成功");
    }

    /**
     * 添加菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        return R.success("添加成功");
    }

    /**
     * 批量停售菜品
     *
     * @param ids
     * @return
     */
    @PostMapping("/status/0")
    public R<String> update(Long[] ids) {
        Dish dish = new Dish();
        dish.setStatus(0);
        for (Long id : ids) {
            LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Dish::getId, id);
            dishService.update(dish, queryWrapper);
        }
        return R.success("修改成功");
    }


    @PostMapping("/status/1")
    public R<String> updates(Long[] ids) {
        Dish dish = new Dish();
        dish.setStatus(1);
        for (Long id : ids) {
            LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Dish::getId, id);
            dishService.update(dish, queryWrapper);
        }
        return R.success("修改成功");
    }


    @GetMapping("{id}")
    public R<DishDto> update(@PathVariable Long id) {
        //查出来一个菜品对象
        Dish dish = dishService.getById(id);
        //构建菜品口味条件查询器
        LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
        //根据这个菜品的id去找口味表
        queryWrapper1.eq(DishFlavor::getDishId, dish.getId());
        //返回一个该菜品的口味集合
        List<DishFlavor> list = dishFlavorService.list(queryWrapper1);
        //创建一个菜品口味对象
        DishDto dishDto = new DishDto();
        //把口味信息设置进去
        dishDto.setFlavors(list);
        //把原来的菜品信息拷贝到这个包含口味与分类名字的对象
        BeanUtils.copyProperties(dish, dishDto);
        //返回该对象
        return R.success(dishDto);
    }

    /**
     * 修改菜品信息,这里要更新两张表
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        //更新菜品表
        dishService.updateById(dishDto);
        //根据DishID查询到对应的菜品口味表
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        //删除对应的菜品口味表
        dishFlavorService.remove(lambdaQueryWrapper);
        //获取到新提交过来的口味信息,循环遍历设置上Dish菜品id
        List<DishFlavor> list = dishDto.getFlavors();
        list = list.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        //批量添加
        dishFlavorService.saveBatch(list);
        return R.success("修改成功");
    }


    @GetMapping("/list")
    public R<List<DishDto>> save(Dish dish) {
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dish::getCategoryId, dish.getCategoryId())
                .eq(Dish::getStatus, 1);
        //查出来所有的菜品信息
        List<Dish> list = dishService.list(lambdaQueryWrapper);
        List<DishDto> lists = list.stream().map((itam) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(itam, dishDto);
            Category category = categoryService.getById(itam.getCategoryId());

            if (category!=null){
                dishDto.setCategoryName(category.getName());
            }
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId, itam.getId());
            //获取每个菜品对应的口味信息
            List<DishFlavor> list1 = dishFlavorService.list(queryWrapper);
                    dishDto.setFlavors(list1);
                    return dishDto;
                }
        ).collect(Collectors.toList());
        return R.success(lists);
    }
}
